Lists

Basic Lists


In [169]:
my_cars = ['BMW 320', 'Benz C class', 'Porshe', 'Maruthi 800']

In [170]:
len(my_cars)


Out[170]:
4

In [171]:
print my_cars[0]


BMW 320

In [172]:
print my_cars[1]


Benz C class

In [173]:
print my_cars[10000]


---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-173-32137b93c120> in <module>()
----> 1 print my_cars[10000]

IndexError: list index out of range

Does not clone by default


In [174]:
my_favourites = my_cars

In [175]:
type(my_cars)


Out[175]:
list

In [176]:
my_favourites.append("Tesla Model S")

In [177]:
my_cars


Out[177]:
['BMW 320', 'Benz C class', 'Porshe', 'Maruthi 800', 'Tesla Model S']

+ operator works just fine


In [178]:
awesome_people = ["T.R", "Vijaykanth"]

In [179]:
awesome_cars = ["BMW", "Merc"]

In [180]:
awesome_things = awesome_people + awesome_cars

In [181]:
awesome_things


Out[181]:
['T.R', 'Vijaykanth', 'BMW', 'Merc']

In [182]:
awesome_cars + awesome_people


Out[182]:
['BMW', 'Merc', 'T.R', 'Vijaykanth']

Traversing a list


In [183]:
for car in my_cars:
    print car, "is my car!"


BMW 320 is my car!
Benz C class is my car!
Porshe is my car!
Maruthi 800 is my car!
Tesla Model S is my car!

Note: Do NOT add or remove an element during iteration


In [184]:
def cube(x):
    return x*x*x

nums = [1,2,3,4,5,6]
cubed_nums = []
for num in nums:
    cubed_nums.append(cube(num))
    
print cubed_nums


[1, 8, 27, 64, 125, 216]

Checking if list contains an element


In [185]:
"BMW 320" in my_cars


Out[185]:
True

In [187]:
if "BMW 320" in my_cars:
    print "i am a rich man"


i am a rich man

In [186]:
"Maruthi Zen" in my_cars


Out[186]:
False


In [188]:
a_string = "Hello World"
for every_character in a_string:
    print "[" + every_character + "]"


[H]
[e]
[l]
[l]
[o]
[ ]
[W]
[o]
[r]
[l]
[d]

In [189]:
long_string = "The quick brown fox jumps over the lazy dog"

In [190]:
long_string.split(" ")


Out[190]:
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']

In [191]:
long_string.title()


Out[191]:
'The Quick Brown Fox Jumps Over The Lazy Dog'

In [194]:
cap_words = []
for word in long_string.split():
    cap_words.append(word.capitalize())
    
cap_words


Out[194]:
['The', 'Quick', 'Brown', 'Fox', 'Jumps', 'Over', 'The', 'Lazy', 'Dog']

In [196]:
"_".join(cap_words)


Out[196]:
'The_Quick_Brown_Fox_Jumps_Over_The_Lazy_Dog'

In [197]:
" ".join([1,2,3])


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-197-a74a1b54c8da> in <module>()
----> 1 " ".join([1,2,3])

TypeError: sequence item 0: expected string, int found

Ranges


In [198]:
range(10)


Out[198]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [200]:
for i in range(10):
    print i


0
1
2
3
4
5
6
7
8
9

In [201]:
range(5, 10)


Out[201]:
[5, 6, 7, 8, 9]

In [202]:
range(5, 10, 2)


Out[202]:
[5, 7, 9]

In [203]:
for num in range(10):
    print cube(num)


0
1
8
27
64
125
216
343
512
729

Using a while loop


In [204]:
i=0
while i < len(my_cars):
    print my_cars[i]
    i += 2


BMW 320
Porshe
Tesla Model S

In [ ]:
my_cars

Methods on Lists

Append


In [205]:
my_cars = []

In [206]:
my_cars


Out[206]:
[]

In [207]:
my_cars.append("BMW 320")

In [208]:
my_cars.append("Tesla Model S")

In [209]:
my_cars


Out[209]:
['BMW 320', 'Tesla Model S']

Note: Doesn't return a new list, modifies the original


Insert


In [210]:
my_cars


Out[210]:
['BMW 320', 'Tesla Model S']

In [211]:
my_cars.insert(0, "Merc C Class")

In [212]:
my_cars


Out[212]:
['Merc C Class', 'BMW 320', 'Tesla Model S']

Extend


In [213]:
his_cars = ["Maruthi 800"]

In [214]:
my_cars


Out[214]:
['Merc C Class', 'BMW 320', 'Tesla Model S']

In [215]:
my_cars.extend(his_cars)

In [216]:
my_cars


Out[216]:
['Merc C Class', 'BMW 320', 'Tesla Model S', 'Maruthi 800']

In [217]:
a = [1,2]

In [218]:
b = [3,4]

In [219]:
a.append(b)

In [220]:
a


Out[220]:
[1, 2, [3, 4]]

Index


In [221]:
my_cars.index("BMW 320")


Out[221]:
1

In [222]:
my_cars[1]


Out[222]:
'BMW 320'

In [223]:
my_cars.index("Porshe")


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-223-9418d51d0ea0> in <module>()
----> 1 my_cars.index("Porshe")

ValueError: 'Porshe' is not in list

Remove


In [224]:
my_cars.remove("BMW 320")

In [225]:
my_cars


Out[225]:
['Merc C Class', 'Tesla Model S', 'Maruthi 800']

In [226]:
my_cars.remove("BMW 320")


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-226-f626228cdf13> in <module>()
----> 1 my_cars.remove("BMW 320")

ValueError: list.remove(x): x not in list

Sort


In [227]:
my_cars


Out[227]:
['Merc C Class', 'Tesla Model S', 'Maruthi 800']

In [228]:
my_cars.sort()

In [229]:
my_cars


Out[229]:
['Maruthi 800', 'Merc C Class', 'Tesla Model S']

Reverse


In [230]:
my_cars


Out[230]:
['Maruthi 800', 'Merc C Class', 'Tesla Model S']

In [231]:
my_cars.reverse()

In [232]:
my_cars


Out[232]:
['Tesla Model S', 'Merc C Class', 'Maruthi 800']

Pop


In [233]:
my_cars


Out[233]:
['Tesla Model S', 'Merc C Class', 'Maruthi 800']

In [234]:
my_cars.pop()


Out[234]:
'Maruthi 800'

In [235]:
my_cars


Out[235]:
['Tesla Model S', 'Merc C Class']

In [236]:
my_cars.pop(0)


Out[236]:
'Tesla Model S'

In [237]:
my_cars


Out[237]:
['Merc C Class']

Note: All of the above methods work IN-PLACE, meaning that they don't return any result


Slicing in Lists


In [238]:
till_100 = range(100)

In [239]:
till_100


Out[239]:
[0,
 1,
 2,
 3,
 4,
 5,
 6,
 7,
 8,
 9,
 10,
 11,
 12,
 13,
 14,
 15,
 16,
 17,
 18,
 19,
 20,
 21,
 22,
 23,
 24,
 25,
 26,
 27,
 28,
 29,
 30,
 31,
 32,
 33,
 34,
 35,
 36,
 37,
 38,
 39,
 40,
 41,
 42,
 43,
 44,
 45,
 46,
 47,
 48,
 49,
 50,
 51,
 52,
 53,
 54,
 55,
 56,
 57,
 58,
 59,
 60,
 61,
 62,
 63,
 64,
 65,
 66,
 67,
 68,
 69,
 70,
 71,
 72,
 73,
 74,
 75,
 76,
 77,
 78,
 79,
 80,
 81,
 82,
 83,
 84,
 85,
 86,
 87,
 88,
 89,
 90,
 91,
 92,
 93,
 94,
 95,
 96,
 97,
 98,
 99]

In [240]:
till_100[:5]


Out[240]:
[0, 1, 2, 3, 4]

In [241]:
till_100[-5:]


Out[241]:
[95, 96, 97, 98, 99]

In [242]:
till_100[0] = "Booga"

In [250]:
for i in till_100[:5]:
    print type(i) is int


False
True
True
True
True

In [247]:
help(instance of)


  File "<ipython-input-247-4697f9012d87>", line 1
    help(instance of)
                   ^
SyntaxError: invalid syntax

In [252]:
isinstance("hello", str)


Out[252]:
True

In [245]:
till_100[:5]


Out[245]:
['Booga', 1, 2, 3, 4]

Exercises

  • A and B of basic/list1.py